/*
 * Copyright 2003-2007 (c) Live Media Pty Ltd. <argot@einet.com.au> 
 *
 * This software is licensed under the Argot Public License 
 * which may be found in the file LICENSE distributed 
 * with this software.
 *
 * More information about this license can be found at
 * http://www.einet.com.au/License
 * 
 * The Developer of this software is Live Media Pty Ltd,
 * PO Box 4591, Melbourne 3001, Australia.  The license is subject 
 * to the law of Victoria, Australia, and subject to exclusive 
 * jurisdiction of the Victorian courts.
 */
package com.colony.networkvm.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.argot.TypeLibrary;

import com.argot.remote.MetaInterface;
import com.argot.remote.MetaLocation;
import com.argot.remote.MetaMethod;
import com.argot.remote.MetaParameter;

import com.colony.networkvm.NvmEnvironment;
import com.colony.networkvm.instruction.NvmLoadCRLObject;
import com.colony.networkvm.instruction.NvmLoadHeapObject;
import com.colony.networkvm.instruction.NvmReturn;
import com.colony.networkvm.instruction.NvmStoreHeapObject;
import com.colony.networkvm.instruction.NvmToHostInstruction;
import com.colony.networkvm.machine.NvmInstance;
import com.colony.remote.RemoteException;
import com.colony.remote.RemoteRuntimeException;

public class NvmMetaStub
implements InvocationHandler
{
	String _host;
	NvmEnvironment _environment;
	MetaLocation _location;
	MetaInterface _metaInterface;
	Class _stub;
	
	public NvmMetaStub( String host, MetaLocation location, NvmEnvironment environment, MetaInterface metaInterface )
	{
		_host = host;
		_location = location;
		_environment = environment;
		_metaInterface = metaInterface;
	}

	public Object invoke(Object proxy, Method method, Object[] args)
	throws Throwable
	{
		// First look for a client side stub that will override
		// the default request mechanism.
		Method stubMethod = null;
		try
		{
			// The method we're looking for must have the same
			// parameters as the original method.
			if ( args != null )
			{
				Class[] cargs = method.getParameterTypes();
					
				stubMethod = this.getClass().getMethod( method.getName(), cargs );
			}	
			else
			{
				stubMethod = this.getClass().getMethod( method.getName(), (Class[]) null );
			}
		}
		catch (SecurityException e)
		{
		}
		catch (NoSuchMethodException e)
		{
		}
		
		// We have an overriding method handler.
		if ( stubMethod != null )
		{
			try
			{
				return stubMethod.invoke( this, args );
			}
			catch (IllegalArgumentException e1)
			{
				throw e1;
			}
			catch (IllegalAccessException e1)
			{
				throw e1;
			}
			catch (InvocationTargetException e1)
			{
				throw e1.getTargetException();
			}
		}
		
		// No handler was found.  Use the default request method.
		NvmInstance nvm = _environment.getNvmInstance();

		TypeLibrary library = nvm.getTypeLibrary();
		
		nvm.push( _host );

		nvm.addInstruction( new NvmToHostInstruction() );

		// Find the MetaMethod information.
		MetaMethod mMethod = _metaInterface.getMetaMethod( method );
		if ( mMethod == null )
		{
			throw new RemoteException("method interface not defined");
		}
		
		MetaParameter[] requestIds = mMethod.getRequestTypes();
		
		// push the values on the stack backwards.
		for ( int x=requestIds.length-1; x >= 0; x-- )
		{
			int heapId = nvm.addHeapObject( requestIds[x].getParamType(), args[x] );
			nvm.addInstruction( new NvmLoadHeapObject(heapId));
		}		

		int objLocation = nvm.addHeapObject( MetaLocation.TYPENAME, _location );
		nvm.addInstruction( new NvmLoadHeapObject(objLocation));
		nvm.addInstruction( new NvmLoadCRLObject() );
		nvm.addInstruction( new NvmMetaMethodCall( mMethod.getMemberTypeId() ));
				
		Class retType = method.getReturnType();		
		if (  !(retType == Void.class || retType == void.class) )
		{
		
			library.getId( retType );
			nvm.addInstruction( new NvmStoreHeapObject(0));
		}
				
		nvm.addInstruction( new NvmReturn() );
		
		_environment.executeInstance( nvm );
		
		if ( nvm.hasException() )
		{
			// if the exception returned is declared, throw it.
			Throwable throwable = nvm.getException();
			Class exceptionTypes[] = method.getExceptionTypes();
			for (int x=0;x<exceptionTypes.length;x++)
			{
				if (exceptionTypes[x].isAssignableFrom(throwable.getClass()))
				{
					throw throwable;
				}
			}

			// if the exception isn't declared, throw a remoteRuntimeException.
			throw new RemoteRuntimeException("Exception not declared",throwable);
		}

		if ( retType == Void.class || retType == void.class )
			return null;
		
		return nvm.getHeapObject(0);
	}

}
